<style lang="less">
#transport-map {
  width: 100%;
  height: 470px;
  position: relative;
}
.amap-sug-result {
  z-index: 99999;
}
</style>
<template>
  <div class="search">
    <Row>
      <Col>
        <Card>
          <Row>
            <Form
              ref="searchForm"
              :model="searchForm"
              inline
              :label-width="100"
              class="search-form"
            >
              <Form-item label="企业名称" prop="companyName">
                <Input
                  type="text"
                  v-model="searchForm.companyName"
                  clearable
                  placeholder="请输入企业名称"
                  style="width: 200px"
                />
              </Form-item>

              <Form-item style="margin-left:-35px;" class="br">
                <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                <Button @click="handleReset">重置</Button>
              </Form-item>
            </Form>
          </Row>
          <Row class="operation">
            <Button @click="add" v-has="'add'" type="primary" icon="md-add">新增运输企业</Button>
          </Row>
          <!-- <Row>
            <Alert show-icon>
              已选择
              <span class="select-count">{{selectCount}}</span> 项
              <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
          </Row>-->
          <Row>
            <Table
              :loading="loading"
              max-height="600"
              border
              :columns="columns"
              :data="data"
              sortable="custom"
              @on-sort-change="changeSort"
              @on-selection-change="showSelect"
              ref="table"
            ></Table>
            <Table
              :columns="exportColumns"
              :data="exportData"
              ref="exportTable"
              style="display:none"
            ></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page
              :current="searchForm.current"
              :total="total"
              :page-size="searchForm.size"
              @on-change="changePage"
              @on-page-size-change="changePageSize"
              :page-size-opts="[10,20,50,100]"
              size="small"
              show-total
              show-elevator
              show-sizer
            ></Page>
          </Row>
        </Card>
      </Col>
    </Row>

    <Modal
      :title="modalTitle"
      v-model="transportModalVisible"
      :mask-closable="false"
      :width="1000"
      :styles="{top: '30px'}"
    >
      <Form ref="transportForm" :model="transportForm" :label-width="120" :rules="rulesForm">
        <Row>
          <Col span="12">
            <Form-item label="企业名称" prop="companyName">
              <Input
                type="text"
                v-model="transportForm.companyName"
                clearable
                placeholder="请输入企业名称"
                style="width: 300px"
              />
            </Form-item>
            <Form-item label="所属地区">
              <div style="display:flex;">
                <al-cascader data-type="all" v-model="areaArr" level="2" style="width:300px;" />
              </div>
            </Form-item>
            <Form-item label="所属部门" prop="deptId">
              <department-tree-choose @on-change="handleSelectDepTree" ref="depTree"></department-tree-choose>
            </Form-item>
            <Form-item label="运营类型" prop="operationType">
              <Select v-model="transportForm.operationType" style="width: 200px" :transfer="true">
                <Option
                  v-for="item in operationTypeSelect"
                  :value="item.value"
                  :key="item.value"
                >{{ item.label }}</Option>
              </Select>
            </Form-item>

            <Form-item label="负责人" prop="managerName">
              <Input
                type="text"
                v-model="transportForm.managerName"
                clearable
                placeholder="请输入负责人"
                style="width: 300px"
              />
            </Form-item>
            <Form-item label="负责人电话" prop="managerMobile">
              <Input
                type="text"
                v-model="transportForm.managerMobile"
                clearable
                placeholder="请输入负责人电话"
                style="width: 300px"
              />
            </Form-item>
            <Form-item label="邮箱" prop="email">
              <Input
                type="text"
                v-model="transportForm.email"
                clearable
                placeholder="请输入邮箱"
                style="width: 300px"
              />
            </Form-item>
            <Form-item label="经营范围" prop="businessScope">
              <Input
                type="text"
                v-model="transportForm.businessScope"
                clearable
                placeholder="请输入经营范围"
                style="width: 300px"
              />
            </Form-item>
            <Form-item label="许可证号" prop="licence">
              <Input
                type="text"
                v-model="transportForm.licence"
                clearable
                placeholder="请输入许可证号"
                style="width: 300px"
              />
            </Form-item>
            <Form-item label="企业状态" prop="companyStatus">
              <Select v-model="transportForm.companyStatus" style="width:200px">
                <Option
                  v-for="item in enterpriseStatus"
                  :value="item.value"
                  :key="item.value"
                >{{ item.label }}</Option>
              </Select>
            </Form-item>
            <Form-item label="企业类型" prop="companyType">
              <Select v-model="transportForm.companyType" style="width:200px">
                <Option
                  v-for="item in enterpriseType"
                  :value="item.value"
                  :key="item.value"
                >{{ item.label }}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col span="12">
            <Input
              v-model="searchAddr"
              placeholder="请输入地址搜索"
              style="width: 482px;margin-bottom:10px;"
              element-id="transport-tipinput"
              search="true"
              @on-search="onSearchPlace"
            />
            <div id="transport-map"></div>
            <Row style="margin-top:10px;">
              <Col span="6">
                <Button type="warning" icon="ios-brush" @click="startDraw">开始绘制</Button>
              </Col>
              <Col span="9">
                <Form-item label="纬度" :label-width="50" prop="lat">
                  <Input
                    type="text"
                    v-model="transportForm.lat"
                    clearable
                    placeholder="请输入纬度"
                    style="width: 130px"
                  />
                </Form-item>
              </Col>
              <Col span="9">
                <Form-item label="经度" :label-width="50" prop="lng">
                  <Input
                    type="text"
                    v-model="transportForm.lng"
                    clearable
                    placeholder="请输入经度"
                    style="width: 130px"
                  />
                </Form-item>
              </Col>
            </Row>
            <Form-item label="企业地址" :label-width="80" prop="companyAddr">
              <Input
                type="text"
                v-model="transportForm.companyAddr"
                clearable
                placeholder="请输入企业地址"
                style="width: 402px"
              />
            </Form-item>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="text" @click="transportModalVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submit">提交</Button>
      </div>
    </Modal>

    <check-password ref="checkPass" @on-success="resetPass" />
  </div>
</template>

<script>
import AMap from "AMap";
let mouseTool = null;
import {
  getCompanyPageList,
  addCompany,
  deleteCompany,
  updateCompany
} from "@/api/index";
import {
  validateMobile,
  validateLng,
  validateLat,
  validateEMail
} from "@/libs/validate";

import {
  enterpriseType,
  enterpriseStatus,
  operationTypeSelect
} from "@/libs/dict";
import departmentChoose from "../../my-components/xboot/department-choose";
import departmentTreeChoose from "../../my-components/xboot/department-tree-choose";
import uploadPicInput from "../../my-components/xboot/upload-pic-input";
import circleLoading from "../../my-components/circle-loading.vue";
import checkPassword from "@/views/my-components/xboot/check-password";
import util from "@/libs/util.js";

export default {
  name: "transport-manage",
  components: {
    circleLoading,
    departmentChoose,
    departmentTreeChoose,
    uploadPicInput,
    checkPassword
  },
  data() {
    return {
      map: null,
      searchAddr: "",
      modalType: "",
      modalTitle: "",
      areaArr: [],
      enterpriseType: enterpriseType,
      enterpriseStatus: enterpriseStatus,
      operationTypeSelect: operationTypeSelect,
      transportModalVisible: false,
      total: 0,
      data: [],
      searchForm: {
        companyId: "",
        companyName: "",
        companyAddr: "",
        managerName: "",
        managerMobile: "",
        email: "",
        businessScope: "",
        licence: "",
        companyStatus: "",
        companyType: "",
        lat: "",
        lng: "",
        createBy: "",
        createDate: "",
        current: 1,
        size: 10
      },
      transportForm: {
        companyId: "",
        companyName: "",
        companyAddr: "",
        managerName: "",
        managerMobile: "",
        operationType: "",
        email: "",
        businessScope: "",
        licence: "",
        companyStatus: "",
        companyType: "",
        lat: "",
        lng: "",
        createBy: "",
        createDate: ""
      },
      rulesForm: {
        companyName: [
          { required: true, message: "企业名不能为空", trigger: "blur" }
        ],
        operationType: [
          {
            required: true,
            message: "运营类型必选",
            trigger: "change",
            type: "number"
          }
        ],
        managerMobile: [
          { required: true, message: "手机号不得为空", trigger: "blur" },
          { validator: validateMobile }
        ],
        email: [
          { required: false, message: "手机号不得为空", trigger: "blur" },
          { validator: validateEMail }
        ],
        companyAddr: [
          { required: true, message: "企业地址不能为空", trigger: "blur" }
        ],
        managerName: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        businessScope: [
          { required: true, message: "企业状态不能为空", trigger: "blur" }
        ],
        licence: [
          { required: true, message: "许可证号不能为空", trigger: "blur" }
        ],
        companyType: [
          {
            required: true,
            message: "企业类型不能为空",
            trigger: "change",
            type: "number"
          }
        ],
        companyStatus: [
          {
            required: true,
            message: "请选择状态",
            trigger: "change",
            type: "number"
          }
        ],
        lat: [{ validator: validateLat }],
        lng: [{ validator: validateLng }]
      },
      columns: [
        {
          title: "序号",
          type: "index",
          width: 65,
          align: "center",
          fixed: "left"
        },
        {
          title: "企业名称",
          key: "companyName",
          minWidth: 180,
          sortable: true,
          align: "center"
        },
        {
          title: "企业地址",
          key: "companyAddr",
          width: 140,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "负责人",
          key: "managerName",
          width: 115,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "负责人电话",
          key: "managerMobile",
          width: 150,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "邮箱",
          key: "email",
          width: 200,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "经营范围",
          key: "businessScope",
          width: 200,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "许可证号",
          key: "licence",
          width: 200,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "企业状态",
          key: "companyStatus",
          align: "center",
          minWidth: 120,
          render: (h, params) => {
            if (params.row.companyStatus == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "营业"
                  }
                })
              ]);
            } else if (params.row.companyStatus == 2) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "停业"
                  }
                })
              ]);
            } else if (params.row.companyStatus == 3) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "整改"
                  }
                })
              ]);
            } else if (params.row.companyStatus == 4) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "停业整顿"
                  }
                })
              ]);
            } else if (params.row.companyStatus == 5) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "歇业"
                  }
                })
              ]);
            } else if (params.row.companyStatus == 6) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "注销"
                  }
                })
              ]);
            }
          },
          filters: [
            {
              label: "正常",
              value: 1
            },
            {
              label: "停业",
              value: 2
            },
            {
              label: "整改",
              value: 3
            },
            {
              label: "停业整顿",
              value: 4
            },
            {
              label: "歇业",
              value: 5
            },
            {
              label: "注销",
              value: 6
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            if (value == 1) {
              return row.companyStatus == 1;
            } else if (value == 2) {
              return row.companyStatus == 2;
            } else if (value == 3) {
              return row.companyStatus == 3;
            } else if (value == 4) {
              return row.companyStatus == 4;
            } else if (value == 5) {
              return row.companyStatus == 5;
            } else if (value == 6) {
              return row.companyStatus == 6;
            }
          }
        },
        {
          title: "企业类型",
          key: "companyType",
          align: "center",
          minWidth: 120,
          render: (h, params) => {
            if (params.row.companyType == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "企业"
                  }
                })
              ]);
            } else if (params.row.companyType == 2) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "个体"
                  }
                })
              ]);
            }
          },
          filters: [
            {
              label: "企业",
              value: 1
            },
            {
              label: "个体",
              value: 2
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            if (value == 1) {
              return row.companyType == 1;
            } else if (value == 2) {
              return row.companyType == 2;
            }
          }
        },
        {
          title: "纬度",
          key: "lat",
          align: "center",
          fixed: "center",
          width: 100
        },
        {
          title: "经度",
          key: "lng",
          align: "center",
          fixed: "center",
          width: 100
        },
        {
          title: "创建人",
          key: "createBy",
          align: "center",
          fixed: "center",
          width: 100
        },
        {
          title: "创建时间",
          key: "createTime",
          fixed: "center",
          align: "center",
          sortable: true,
          sortType: "desc",
          width: 150
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  directives: [
                    {
                      name: "has",
                      value: "edit"
                    }
                  ],
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  directives: [
                    {
                      name: "has",
                      value: "delete"
                    }
                  ],
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    };
  },
  methods: {
    init() {
      this.loadGetCompanyPageList();
      this.mapInit();
    },
    mapInit() {
      this.map = new AMap.Map("transport-map", {
        resizeEnable: true,
        zoom: 5
      });
      let self = this;
      this.map.plugin(["AMap.MapType"], function() {
        //地图类型切换
        var type = new AMap.MapType({
          defaultType: 0 //使用2D地图
        });
        self.map.addControl(type);
      });
      this.map.plugin(["AMap.ToolBar"], function() {
        //加载工具条
        var tool = new AMap.ToolBar();
        self.map.addControl(tool);
      });
      this.map.plugin(["AMap.MouseTool"], function() {
        //鼠标工具插件
        mouseTool = new AMap.MouseTool(self.map);
      });
      AMap.event.addListener(mouseTool, "draw", function(event) {
        // event.obj 为绘制出来的覆盖物对象
        let drawObj = event.obj;

        var point = drawObj.getPosition();
        self.transportForm.lat = point.lat;
        self.transportForm.lng = point.lng;

        mouseTool.close(false);
      });
      //输入提示
      var autoOptions = {
        input: "transport-tipinput"
      };
      var placeSearch = null;
      var auto = null;
      this.map.plugin(["AMap.Autocomplete"], function() {
        auto = new AMap.Autocomplete(autoOptions);
      });

      this.map.plugin(["AMap.PlaceSearch"], function() {
        placeSearch = new AMap.PlaceSearch({
          map: self.map
        }); //构造地点查询类
      });

      AMap.event.addListener(auto, "select", select); //注册监听，当选中某条记录时会触发
      function select(e) {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name); //关键字查询查询
      }
    },
    onSearchPlace() {
      let addr = this.searchAddr;
      let self = this;
      AMap.plugin("AMap.Geocoder", function() {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        });

        geocoder.getLocation(addr, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            // result中对应详细地理坐标信息
            var location = result.geocodes[0].location;
            try {
              if (location) {
                self.map.setZoomAndCenter(14, [location.lng, location.lat]);
              } else {
                self.$Message.error("未查询到地理信息!");
              }
            } catch (error) {
              self.$Message.error("查询地理信息失败,请检查网络!");
            }
          } else {
            self.$Message.error("未查询到地理信息!");
          }
        });
      });
    },
    startDraw() {
      this.map.clearMap();
      //打点
      mouseTool.marker({});
      this.$Message.info("点击鼠标左键确定点");
    },
    handleSelectDepTree(v) {
      this.transportForm.deptId = v[0];
    },
    handleSelectDep(v) {
      this.searchForm.deptId = v;
    },
    changePage(v) {
      this.searchForm.current = v;
      this.loadGetCompanyPageList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.size = v;
      this.loadGetCompanyPageList();
    },
    selectDateRange(v) {
      if (v) {
        this.searchForm.startDate = v[0];
        this.searchForm.endDate = v[1];
      }
    },
    loadGetCompanyPageList() {
      // 多条件搜索用户列表
      this.loading = true;
      // 避免后台默认值
      if (!this.searchForm.type) {
        this.searchForm.type = "";
      }
      if (!this.searchForm.status) {
        this.searchForm.status = "";
      }
      getCompanyPageList(this.searchForm).then(res => {
        this.loading = false;
        console.log("getCompanyPageList", res);
        if (res.code == 0) {
          this.data = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    handleSearch() {
      this.searchForm.current = 1;
      this.searchForm.size = 20;
      this.loadGetCompanyPageList();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.current = 1;
      this.searchForm.size = 20;
      this.selectDate = null;
      this.searchForm.startDate = "";
      this.searchForm.endDate = "";
      this.selectDep = [];
      this.searchForm.departmentId = "";
      // 重新加载数据
      this.loadGetCompanyPageList();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order == "normal") {
        this.searchForm.order = "";
      }
      this.loadGetCompanyPageList();
    },
    getRoleList() {
      getRoleSelect().then(res => {
        if (res.code == 0) {
          this.roleList = res.data;
        }
      });
    },
    handleDropdown(name) {
      if (name == "refresh") {
        this.loadGetCompanyPageList();
      } else if (name == "reset") {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未选择要重置密码的用户");
          return;
        }
        this.$refs.checkPass.show();
      } else if (name == "exportData") {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未选择要导出的数据");
          return;
        }
        this.$Modal.confirm({
          title: "确认导出",
          content: "您确认要导出所选 " + this.selectCount + " 条数据?",
          onOk: () => {
            this.$refs.exportTable.exportCsv({
              filename: "用户数据"
            });
          }
        });
      } else if (name == "exportAll") {
        this.transportModalVisible = true;
      }
    },
    exportAll() {
      getAllUserData().then(res => {
        this.transportModalVisible = false;
        if (res.success) {
          this.exportData = res.result;
          setTimeout(() => {
            this.$refs.exportTable.exportCsv({
              filename: "用户全部数据"
            });
          }, 1000);
        }
      });
    },
    add() {
      this.modalType = 0;
      this.modalTitle = "添加企业";
      this.$refs.transportForm.resetFields();
      this.areaArr = [];
      this.transportModalVisible = true;
    },
    edit(v) {
      this.modalType = 1;
      this.modalTitle = "编辑企业";
      this.$refs.transportForm.resetFields();
      // 转换null为""
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.transportForm = data;
      this.areaArr = this.transportForm.areaCode.split(",");
      this.$refs.depTree.setData(this.transportForm.deptName);
      this.map.clearMap();
      if (this.transportForm.lat && this.transportForm.lng) {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(
            this.transportForm.lng,
            this.transportForm.lat
          ) // 圆心位置
        });
        this.map.add(marker);
        this.map.setFitView();
      }

      this.transportModalVisible = true;
    },
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除企业 " + v.companyName + " ?",
        loading: true,
        onOk: () => {
          deleteCompany(v.companyId).then(res => {
            this.$Modal.remove();
            if (res.code == 0) {
              this.$Message.success("删除成功");
              this.loadGetCompanyPageList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    dropDown() {},
    showSelect(e) {},
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    delAll() {},
    /**
     * 提交新增运营商
     * @param newForm
     */
    submit() {
      let _this = this;
      if (_this.modalType == 0) {
        console.log("submit", this.transportForm);
        _this.$refs.transportForm.validate(valid => {
          if (valid) {
            let obj = util.deepClone(_this.transportForm);
            obj.areaCode = this.areaArr.map(item => item.code).join(",");
            obj.areaName = this.areaArr.map(item => item.name).join(",");
            this.areaArr = [];
            console.log("submit", obj);
            addCompany(_this.transportForm).then(
              res => {
                console.log("submit response", JSON.stringify(res));
                _this.$refs.transportForm.resetFields();
                _this.transportModalVisible = false;
                _this.loadGetCompanyPageList();
              },
              error => {
                console.log("submit error", JSON.stringify(error));
              }
            );
          }
        });
      } else {
        console.log("submitUser", this.transportForm);
        this.$refs.transportForm.validate(valid => {
          if (valid) {
            let obj = util.deepClone(_this.transportForm);
            obj.areaCode = this.areaArr.map(item => item.code).join(",");
            obj.areaName = this.areaArr.map(item => item.name).join(",");
            updateCompany(obj).then(
              res => {
                console.log("submitUser response", JSON.stringify(res));
                _this.$refs.transportForm.resetFields();
                _this.transportModalVisible = false;
                _this.loadGetCompanyPageList();
              },
              error => {
                console.log("submitUser error", JSON.stringify(error));
              }
            );
          }
        });
      }
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style scoped>
</style>
